var meterRecordData = [];
var addMeterTime = undefined;
var imgIndex = undefined;
var meterIndex = undefined;
var meterCodes = [];
var meterTypes = [];
var avatar_datas = [];
var uploadFiles = [];
var imgName = ["日期", "时间", "有功(总)", "有功(尖峰)", "有功(峰)", "有功(平)", "有功(谷)", "无功(总)"];
var meterRecords = undefined;

$(document).ready(function() {
	showLoading();
	$('title', parent.document).html($('title').text());
	$("#sureBtn").hide();
	$ajaxList('chargingStation', getChargingStation, {BulidStatus: '3'});
	setBaseUrl();
	setTimeout(hideLoading, 500);
})

function getChargingStation(data) {
	var length = data.length;
	for (var i = 0; i < length; i++) {
		$("#chargingStationID").append("<option value='" + data[i].chargingStationID + "'>" + data[i].chargingStationName + "</option>");
	}
	$("#chargingStationID").tips({
		side : 2,
		msg : "请选择充电站",
		bg : '#AE81FF',
		time : 1
	});
	$("#chargingStationID").focus();
}

function search(){
	$("#saveMeterTime").html('');
	$("#meterSaveMsg").html('');
	$("#sureBtn").hide();
	if (!$("#chargingStationID").val()) {
		$("#chargingStationID").tips({
			side : 2,
			msg : "请选择充电站",
			bg : '#AE81FF',
			time : 1
		});
		$("#chargingStationID").focus();
		setTimeout(hideLoading, 500);
		return;
	}
	$("#sureBtn").show();
	$ajax('searchMeterInfoAndRecord', {chargingStationID : $("#chargingStationID").val()}, searchMeterRecordSave);
}
function searchMeterRecordSave(data){
	meterRecordData = data && data.meterRecordList || [];
	var meterSaveMsg = $("#meterSaveMsg");
	var length = 0;
	length = meterRecordData.length;
	for (var i = 0; i < length; i++) {
		$("#saveMeterTime").html(timeStamp2String(getSystemTime().getTime()));
		$("#sureBtn").attr("hidden",false);
		var fourTable = createDiv('table',{'class':'table table-responsive fourTable'});
	      var $tr2 = $('<tr>').appendTo(fourTable);
	          $("<td rowspan='8' class='meterSaveTdTwo'>").html(
	        		  '<span id="meterMsg'+ i +'">' + "表号:" + (meterRecordData[i].meterCode || '-') +'</span><br>'+
	        		  '<span id="meterMsg'+ i +'">' + "倍率:" + (meterRecordData[i].meterRate || '-') +'</span>').appendTo($tr2);
	          $("<td class='meterSaveTdOne'>").html('<label class="col-sm-1 control-label">日期</label>').appendTo($tr2);
	          $("<td class='meterSaveTdOne'>").html(meterRecordData[i].meterDate || '-').appendTo($tr2);
	          $("<td id='" + meterRecordData[i].meterCode + "0' class='meterSaveTdThree'>").html('<button type="button" class="btn" aria-label="Left Align" onclick="getImg('+ i +', 0)">添加图片</button>').appendTo($tr2);
	          $("<td class='meterSaveTdThree'>").html(
	        		 '<div id="meterDate' + i + '" class="input-group date" data-date-format="yyyy-mm-dd">' + 
	        		 '<input class="form-control" id="saveMeterDate' + i + '" type="text"/>' + 
	             	 '<span class="input-group-addon"><span class="glyphicon glyphicon-remove"></span></span>' +
	             	 '<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span></span></div>'
	        		  ).appendTo($tr2);
	      var $tr3 = $('<tr>').appendTo(fourTable);
	          $("<td class='meterSaveTdOne'>").html('<label class="col-sm-1 control-label">时间</label>').appendTo($tr3);
	          $("<td class='meterSaveTdOne'>").html(meterRecordData[i].meterTime || '-').appendTo($tr3);
	          $("<td id='" + meterRecordData[i].meterCode + "1' class='meterSaveTdThree'>").html('<button type="button" class="btn" aria-label="Left Align" onclick="getImg('+ i +', 1)">添加图片</button>').appendTo($tr3);
	          $("<td class='meterSaveTdThree'>").html(
	        		  '<div id="meterTime' + i + '" class="input-group date" data-date-format="hh:ii:ss">' + 
	        		  '<input class="form-control date" type="text" id="saveMeterTime'+ i +'" name="saveMeterTime"/>' + 
		              '<span class="input-group-addon"><span class="glyphicon glyphicon-remove"></span></span>' +
		              '<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span></span></div>'
	        		  ).appendTo($tr3);
	      var $tr4 = $('<tr>').appendTo(fourTable);
	          $("<td class='meterSaveTdOne'>").html('<label class="col-sm-1 control-label">有功(总)</label>').appendTo($tr4);
	          $("<td class='meterSaveTdOne'>").html(meterRecordData[i].powerTotal || '-').appendTo($tr4);
	          $("<td id='" + meterRecordData[i].meterCode + "2' class='meterSaveTdThree'>").html('<button type="button" class="btn" aria-label="Left Align" onclick="getImg('+ i +', 2)">添加图片</button>').appendTo($tr4); 
	          $("<td class='meterSaveTdThree'>").html('<input class="form-control" type="text" id="savePowerTotal'+ i +'" name="savePowerTotal"/>').appendTo($tr4);
	      var $tr5 = $('<tr>').appendTo(fourTable);
	          $("<td class='meterSaveTdOne'>").html('<label class="col-sm-1 control-label">有功(尖峰)</label>').appendTo($tr5);
	          $("<td class='meterSaveTdOne'>").html(meterRecordData[i].powerAiguille || '-').appendTo($tr5);
	          $("<td id='" + meterRecordData[i].meterCode + "3' class='meterSaveTdThree'>").html('<button type="button" class="btn" aria-label="Left Align" onclick="getImg('+ i +', 3)">添加图片</button>').appendTo($tr5);
	          $("<td class='meterSaveTdThree'>").html('<input class="form-control" type="text" id="savePowerAiguille'+ i +'" name="savePowerAiguille"/>').appendTo($tr5);
	      var $tr6 = $('<tr>').appendTo(fourTable);
	          $("<td class='meterSaveTdOne'>").html('<label class="col-sm-1 control-label">有功(峰)</label>').appendTo($tr6);
	          $("<td class='meterSaveTdOne'>").html(meterRecordData[i].powerPeak || '-').appendTo($tr6);
	          $("<td id='" + meterRecordData[i].meterCode + "4' class='meterSaveTdThree'>").html('<button type="button" class="btn" aria-label="Left Align" onclick="getImg('+ i +', 4)">添加图片</button>').appendTo($tr6);   
	          $("<td class='meterSaveTdThree'>").html('<input class="form-control" type="text" id="savePowerPeak'+ i +'" name="savePowerPeak"/>').appendTo($tr6);
	      var $tr7 = $('<tr>').appendTo(fourTable);
	          $("<td class='meterSaveTdOne'>").html('<label class="col-sm-1 control-label">有功(平)</label>').appendTo($tr7);
	          $("<td class='meterSaveTdOne'>").html(meterRecordData[i].powerFlat || '-').appendTo($tr7);
	          $("<td id='" + meterRecordData[i].meterCode + "5' class='meterSaveTdThree'>").html('<button type="button" class="btn" aria-label="Left Align" onclick="getImg('+ i +', 5)">添加图片</button>').appendTo($tr7);
	          $("<td class='meterSaveTdThree'>").html('<input class="form-control" type="text" id="savePowerFlat'+ i +'" name="savePowerFlat"/>').appendTo($tr7);
	      var $tr8 = $('<tr>').appendTo(fourTable);
	          $("<td class='meterSaveTdOne'>").html('<label class="col-sm-1 control-label">有功(谷)</label>').appendTo($tr8);
	          $("<td class='meterSaveTdOne'>").html(meterRecordData[i].powerGrain || '-').appendTo($tr8);
	          $("<td id='" + meterRecordData[i].meterCode + "6' class='meterSaveTdThree'>").html('<button type="button" class="btn" aria-label="Left Align" onclick="getImg('+ i +', 6)">添加图片</button>').appendTo($tr8);
	          $("<td class='meterSaveTdThree'>").html('<input class="form-control" type="text" id="savePowerGrain'+ i +'" name="savePowerGrain"/>').appendTo($tr8);
	      var $tr9 = $('<tr>').appendTo(fourTable);
	          $("<td class='meterSaveTdOne'>").html('<label class="col-sm-1 control-label">无功(总)</label>').appendTo($tr9);
	          $("<td class='meterSaveTdOne'>").html(meterRecordData[i].idleTotal || '-').appendTo($tr9);
	          $("<td id='" + meterRecordData[i].meterCode + "7' class='meterSaveTdThree'>").html('<button type="button" class="btn" aria-label="Left Align" onclick="getImg('+ i +', 7)">添加图片</button>').appendTo($tr9);
	          $("<td class='meterSaveTdThree'>").html('<input class="form-control" type="text" id="saveIdleTotal'+ i +'" name="saveIdleTotal"/>').appendTo($tr9);
	      meterSaveMsg.append(fourTable);
		selectDate("meterDate" + i);
		selectDate("meterTime" + i, 0, undefined, 1);
	}
	setTimeout(hideLoading, 500);
}

function getImg(meterCode, meterMsg){
	$("#avatarInput").val('');
	$("#meterTime").val(document.getElementById("saveMeterTime").innerHTML);
	$("#avatar-modal").modal("show");
	imgIndex = meterMsg;
	meterIndex = meterCode;
}

function confirm(){
	meterRecords = [];
	for (var i = 0;i < meterRecordData.length;i++){
		var meterRecord = new MeterRecord();
		meterRecord.chargingStationID = $("#chargingStationID").val();
		meterRecord.meterCode = meterRecordData[i].meterCode;
		meterRecord.meterDate = $("#saveMeterDate" + i).val();
		meterRecord.meterTime = $("#saveMeterTime" + i).val();
		meterRecord.powerTotal = $("#savePowerTotal" + i).val();
		meterRecord.powerAiguille = $("#savePowerAiguille" + i).val();
		meterRecord.powerPeak = $("#savePowerPeak" + i).val();
		meterRecord.powerFlat = $("#savePowerFlat" + i).val();
		meterRecord.powerGrain = $("#savePowerGrain" + i).val();
		meterRecord.idleTotal = $("#saveIdleTotal" + i).val();
		meterRecord.addMeterRecordDate = document.getElementById("saveMeterTime").innerHTML;
		meterRecord.meterMan = $("#saveMeterMan").val();
		meterRecords.push(meterRecord);
		if(!(checkNum("savePowerTotal" + i) && 
			checkNum("savePowerAiguille" + i) && 
			checkNum("savePowerPeak" + i) && 
			checkNum("savePowerFlat" + i) && 
			checkNum("savePowerGrain" + i) && 
			checkNum("saveIdleTotal" + i) && 
			checkNum("saveMeterMan", 3) && 
			checkNum("saveMeterDate" + i, 3) &&
			checkNum("saveMeterTime" + i, 3))){
			return;
		}
	}
	var length = meterRecordData.length * 8;
	var formdata = new FormData();
	for(var i = 0; i < length; i++){
		if(!uploadFiles[i]){
			showMessge("电表" + (meterRecordData[parseInt(i/8)].meterCode || '') + imgName[i%8] + "图片未选择");
			return;
		}
		formdata.append("uploadFiles", uploadFiles[i]);
	}
	formdata.append("meterTime", $("#meterTime").val());
	formdata.append("chargingStationID", $("#chargingStationID").val());
	formdata.append("meterCode", meterCodes);
	formdata.append("meterType", meterTypes);
	formdata.append("avatar_data", avatar_datas);
	showLoading();
	$ajaxFile('addMeterRecordImg', saveFormData, formdata);
}
function saveFormData(data){
	var result = data && data.result;
	if (result == "Success") {
		$ajax("addMeterRecord", {meterRecord : JSON.stringify(meterRecords)}, saveMeterRecord, "", search);
	} else if (result == "NotFound"){
		showMessge("图片上传异常");
	} else {
		showMessge(messageContent["Insert.Error"]);
	}
}
function saveMeterRecord(data){
	var result = data && data.result;
	if (result == "Success") {
		showMessge(messageContent["Insert.Success"], undefined, goback);
	} else if (result == "MeterRecordDateNoNull"){
		showMessge("抄表记录已存在！");
	} else if (result == "NotFound"){
		showMessge(messageContent["Insert.Failed"]);
	} else {
		showMessge(messageContent["Insert.Error"]);
	}
}
function MeterRecord(){
	this.chargingStationID = "";
	this.meterCode = "";
	this.meterDate = "";
	this.meterTime = "";
	this.powerTotal = "";
	this.powerAiguille = "";
	this.powerPeak = "";
	this.powerFlat = "";
	this.powerGrain = "";
	this.idleTotal = "";
	this.addMeterRecordDate = "";
	this.meterMan = "";
}
createDiv=function (t,a,x){
    var e = document.createElement(t);
    if(a){
        for(var k in a){
            if(k == 'class'){
                e.setAttribute(k,a[k]);
            }
            if(k ==  'id'){
                e.setAttribute(k,a[k]);
            }
            e.setAttribute(k,a[k]);
        }
    }
    if(x){
        e.appendChild(document.createTextNode(x));
    }
    return e;
}
function goback() {
	window.parent.skipSecondMenu('costManage/meterRecord', 'meterRecord');
}
function selectImage() {
	if($("#preview").html() == ""){
		$("#avatarInput").tips({
			side : 3,
			msg : "请选择电表" + (meterRecordData[meterIndex].meterCode || '') + imgName[imgIndex] + "图片",
			bg : '#AE81FF',
			time : 2
		});
		$("#avatarInput").focus();
	} else {
		var meterID = meterRecordData[meterIndex].meterCode;
		$("#" + meterID + imgIndex).html('<div class="avatar-preview" onclick="getImg(' + meterIndex + ', ' + imgIndex + ')" style="width: 184px; height: 104.667px;">' + $("#preview").html() + "</div>");
		$("#avatar-modal").modal("hide");
		meterCodes[meterIndex * 8 + imgIndex] = meterID;
		meterTypes[meterIndex * 8 + imgIndex] = imgIndex;
		uploadFiles[meterIndex * 8 + imgIndex] = $("#avatarInput").get(0) && $("#avatarInput").get(0).files && $("#avatarInput").get(0).files[0];
		avatar_datas[meterIndex * 8 + imgIndex] = $(".avatar-data").val();
	}
}
function closeImage() {
	$("#avatar-modal").modal("hide");
}